package com.southwind.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;

@Slf4j
public class IOUtil {
    private IOUtil() {}

    private static final int BUF_SIZE = 2048;

    // 读取文件内容为字符串（显式指定UTF-8编码）
    public static String readAsString(File file) throws IOException {
        try (InputStream in = new FileInputStream(file)) {
            return readAsString(in);
        }
    }

    // 读取类路径资源为字符串（修复流关闭问题）
    public static String readResourceAsString(String resource) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        try (InputStream in = classLoader.getResourceAsStream(resource)) {
            if (in == null) {
                throw new FileNotFoundException("Resource not found: " + resource);
            }
            return readAsString(in);
        } catch (IOException ex) {
            log.error("Error reading resource: {}", resource, ex);
            throw new RuntimeException("Failed to read resource: " + resource, ex);
        }
    }

    // 统一字符编码处理（修复乱码问题）
    public static String readAsString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copy(inputStream, baos);
        return baos.toString(StandardCharsets.UTF_8.name());
    }

    // 写入字符串到文件（显式指定UTF-8编码）
    public static void writeString(File target, String content) throws IOException {
        try (OutputStream fos = new FileOutputStream(target, false)) {
            fos.write(content.getBytes(StandardCharsets.UTF_8));
        }
    }

    // 复制文件夹（增加空目录检查）
    public static void copyFolder(File srcDir, File destDir) throws IOException {
        if (!srcDir.exists()) {
            throw new FileNotFoundException("Source directory not found: " + srcDir.getAbsolutePath());
        }

        if (!destDir.exists() && !destDir.mkdirs()) {
            throw new IOException("Failed to create directory: " + destDir.getAbsolutePath());
        }

        File[] files = srcDir.listFiles();
        if (files == null) {
            return; // 空目录
        }

        for (File file : files) {
            File destFile = new File(destDir, file.getName());
            if (file.isDirectory()) {
                copyFolder(file, destFile);
            } else {
                copyFile(file, destFile);
            }
        }
    }

    // 文件复制（使用try-with-resources）
    public static void copyFile(File src, File dest) throws IOException {
        try (InputStream fis = new FileInputStream(src);
             OutputStream fos = new FileOutputStream(dest, false)) {
            copy(fis, fos);
        }
    }

    // 流复制（缓冲区优化）
    public static void copy(InputStream is, OutputStream os) throws IOException {
        byte[] buffer = new byte[BUF_SIZE];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.flush();
    }

    // 递归删除（增加存在性检查）
    public static boolean removeItem(File item) {
        if (!item.exists()) {
            return false;
        }

        if (item.isDirectory()) {
            File[] files = item.listFiles();
            if (files != null) {
                for (File child : files) {
                    removeItem(child);
                }
            }
        }
        return item.delete();
    }
}